import socket
import logging
import os
import hashlib
import sys
import optparse
import traceback

import sockets.utils as sock_utils
from server import APICodes

FINDME_SERVER = 'localhost'
FINDME_PORT = 9876

mylogger = logging.getLogger( 'pycfindme' )


def pwhash( input ):
    m = hashlib.md5()
    m.update( input )
    return m.hexdigest()


def _write_image( s, picture_url ):
    contents = open( picture_url ).read()
    sock_utils.write_string( s, contents )
    sock_utils.write_string( s, os.path.splitext( picture_url ) )


def add_user( s, username, password, picture_url=None, email=None ):

    sock_utils.write_integer( s, APICodes.ADD_USER )
    sock_utils.write_string( s, username )
    sock_utils.write_string( s, pwhash(password) )
    sock_utils.write_string( s, email if email else '' )
    if not picture_url:
        sock_utils.write_boolean( s, False )
    else:
        sock_utils.write_boolean( s, True )
        _write_image( s, picture_url )
    userid = sock_utils.read_integer(s)
    opstatus = sock_utils.read_integer(s)
    if opstatus != APICodes.SUCCESS:
        raise Exception( "Error while adding user: "
                         "server error code: %d" % ( opstatus, ) )
    mylogger.info( "successfully added user %s: returned userid %d" % ( username, userid ) )


if __name__ == '__main__':

    def usage( err_msg=None ):
        if err_msg:
            print "error: %s\n" % ( err_msg, )
        print "Usage:\n\n%s <username> <password> [email] [picture_url]" % ( sys.argv[0], )
        sys.exit(1)

    parser = optparse.OptionParser( usage="%prog <options>\n\nInteract with the findme server" )
    options, args = parser.parse_args()

    try:
        username = args[0]
        password = args[1]
    except:
        usage( err_msg="specify username and password" )

    email = args[2] if args[2:] else None
    picture_url = args[3] if args[3:] else None

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print >> sys.stderr, "connecting to server at %s:%s ..." % ( FINDME_SERVER, FINDME_PORT )
    s.connect((FINDME_SERVER, FINDME_PORT))

    try:
        add_user( s, username, password, email=email, picture_url=picture_url )
    except:
        print traceback.format_exc()
    finally:
        s.close()
